﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Strategy.Core.TradeTypes;

namespace Strategy.Core.TradeStreams.Indicators
{
    public class RSIIndicatorStream : AIndicator
    {

        protected CandleStream candleStream = null;
        public long Period { get; protected set; }
        private List<double> ganancia = new List<double>();
        private List<double> perdida  = new List<double>();
     
        private RSIIndicatorStream() { }
        public RSIIndicatorStream(CandleStream c,long period)
        {
            Period = period;
            candleStream = c;
        }


        public static string generateID(long period) { return "RSI "+period; }


        protected override double getCalculatedValue(QuoteData qd)
        {
            if (candleStream.Count <= 1)
                return 0;
            double prev = candleStream.getByIndexFromEnd(1).Close;
            double curr = candleStream.getByIndexFromEnd(0).Close;

            double p = 0;
            double g = 0;
            if (curr > prev)
                p = curr - prev;
            else
                g = prev - curr;

            if (isNewInterval(qd))
            {
                perdida.Add(p); ganancia.Add(g);
            }
            else
            {
                perdida [perdida.Count  - 1] = p;
                ganancia[ganancia.Count - 1] = g;
            }

            if (candleStream.Count <= Period)
                return 0;

            double mg = 0;
            double mp = 0;
            for (int i = 0; i < Period; ++i)
            {
                mp += perdida[perdida.Count - 1 -i];
                mg += ganancia[ganancia.Count - 1 -i];
            }
            mp /= Period;
            mg /= Period;
            return 100 - (100 / (1 + mp / mg));

        }

        public override int getLevel()
        {
            return candleStream.getLevel()+1;
        }

        public override string getID()
        {
            return generateID(Period);
        }
    }
}
